import httpx
from mcp.server.fastmcp import FastMCP
from typing import Any

# Initialize FastMCP server
mcp = FastMCP("weather", description="Weather API Server")

NWS_API_BASE_URL = "https://api.weather.gov"
USER_AGENT = "WeatherAPI/1.0"
# Define async function to get weather alerts by state
@mcp.tool()
async def get_alerts(state: str) -> str:
    """Get weather alerts for a given state."""
    url = f"{NWS_API_BASE_URL}/alerts/active/area/{state}"
    data = await make_nws_request(url)
    if not data or "features" not in data:
        return "No active alerts found."
    
    if not data["features"]:
        return "No active alerts found."

	
    alerts = [format_alert(feature) for feature in data["features"]]

    return "\n".join(alerts)


# Define async function to get weather forecast by latitude and longitude
@mcp.tool()
async def get_forecast(latitude: float, longitude: float) -> str:
    """Get weather forecast for a given latitude and longitude."""
        # First, get the grid points for the coordinates
    points_url = f"{NWS_API_BASE_URL}/points/{latitude},{longitude}"
    points_data = await make_nws_request(points_url)
    if not points_data:
        return "No grid points found."

        # Then, get the forecast using the grid points
    forecast_url = points_data["properties"]["forecast"]
    forecast_data = await make_nws_request(forecast_url)
    if not forecast_data:
        return "No forecast data found."

    periods = forecast_data["properties"]["periods"]
    forecasts = []
    for period in periods[:5]:
        forecast = f"""{period['name']}: 温度: {period['temperature']}°{period['temperatureUnit']},
风速: {period['windSpeed']} {period['windDirection']}, 天气: {period['detailedForecast']}"""
        forecasts.append(forecast)
    return "\n------\n".join(forecasts)

async def make_nws_request(url:str)-> dict[str,Any]|None:
	"""Make a request to the NWS API and return the JSON response."""
	headers = {"User-Agent": USER_AGENT, "Accept": "application/geo+json"}
	async with httpx.AsyncClient() as client:
		try:
			response = await client.get(url, headers=headers, timeout=30)
			response.raise_for_status()
			return response.json()
		except httpx.HTTPStatusError as e:
			print(f"HTTP error: {e}")
		except httpx.RequestError as e:
			print(f"Request error: {e}")
		return None

def format_alert(feature: dict[str,Any]) -> str:
    props = feature["properties"]
    return f"""事件: {props.get('event','未知')} 
区域：{props.get('areaDesc','未知')}
严重性：{props.get('severity','未知')}
描述: {props.get('description','无描述')}
指令: {props.get('instruction','无指令')}"""

if __name__ == "__main__":
    # Run the FastMCP server
    mcp.run(transport="stdio")